<!--
 * @Description: 
 * @Author: william
 * @Date: 2025-06-05 14:23:19
 * @LastEditors: william
 * @LastEditTime: 2025-11-10 16:56:53
-->
<template>
  <nw-PageTitle :title="$t('pages.manual')" />
  <nw-PageContainer isTabbar>
    <up-toast ref="uToastRef" />
    <scroll-view class="scroll-content" scroll-y>
      <view class="bg-container" />
      <view class="mc-top">
        <view class="mct-left">
          <view class="manual-title">
            <view class="rcc-label">当前炒菜机：</view>
            <view class="rcc-select">
              <zxz-uni-data-select
                v-model="deviceRow.sn"
                :localdata="deviceList"
                placeholder="选择"
                :emptyTips="$t('system.noOption')"
                :clear="false"
                :disabled="
                  deviceRow.sn && deviceRow.status !== deviceStatus.Idle
                "
                dataKey="name"
                dataValue="sn"
                @change="handleRoleChange"
              ></zxz-uni-data-select>
            </view>
          </view>
          <view class="manual-status">
            炒菜机{{
              g_options.getOptionText(
                g_options.deviceStatusOptions,
                deviceRow.status,
                '--'
              )
            }}
          </view>
        </view>
        <view
          class="mct-right"
          :class="{
            active:
              deviceRow.status === deviceStatus.Idle ||
              deviceRow.status === deviceStatus.ManualCooking
          }"
          @click="handleCook"
        >
          <view class="mctr-top">{{ statusBtnText }}</view>
          <view class="mctr-bottom">烹饪时长{{ cookingDuration }}s</view>
        </view>
      </view>
      <view class="lists">
        <view class="list">
          <view class="list-top">
            <view class="lt-left">火力</view>
            <view class="lt-right">{{ formData.firepower }}档</view>
          </view>
          <view
            :class="[
              'list-slider',
              {
                disabled: deviceRow.status !== deviceStatus.ManualCooking
              }
            ]"
          >
            <view
              :class="[
                'block',
                {
                  active:
                    formData.firepower >= (i === 0 ? 0 : firepowerObj.min + i)
                }
              ]"
              v-for="(v, i) in firepowerObj.max - firepowerObj.min + 1"
              :key="v"
              @click="handleFirepowerChange(i === 0 ? 0 : firepowerObj.min + i)"
            >
              {{ i === 0 ? 0 : firepowerObj.min + i }}
            </view>
          </view>
        </view>
        <view class="list">
          <view class="list-top">
            <view class="lt-left">拌刀</view>
          </view>
          <view class="list-control">
            <view class="lc-left">
              <view class="lcl-item" @click="handleSpatulaSwitch(1)">
                <image
                  :src="
                    getViteImageUrl(
                      `manual/${
                        formData.spatula === 'slewDown'
                          ? 'slewDownActive'
                          : 'slewDown'
                      }.png`
                    )
                  "
                  mode="aspectFit"
                  :class="[
                    'icon',
                    {
                      disabled: deviceRow.status !== deviceStatus.ManualCooking
                    }
                  ]"
                />
                <view class="lc-text">悬臂放下</view>
              </view>
              <view class="lcl-item" @click="handleSpatulaSwitch(2)">
                <image
                  :src="
                    getViteImageUrl(
                      `manual/${
                        formData.spatula === 'slewUp'
                          ? 'slewUpActive'
                          : 'slewUp'
                      }.png`
                    )
                  "
                  mode="aspectFit"
                  :class="[
                    'icon',
                    {
                      disabled: deviceRow.status !== deviceStatus.ManualCooking
                    }
                  ]"
                />
                <view class="lc-text">悬臂抬起</view>
              </view>
            </view>
            <view class="lc-right">
              <view class="lcr-item">
                <view class="lcr-top">
                  <view class="lcrt-left">正转速度</view>
                  <view class="lcrt-right">{{ formData.forwardSpeed }}档</view>
                </view>
                <view
                  :class="[
                    'list-slider',
                    'list-slider-forward',
                    {
                      disabled: deviceRow.status !== deviceStatus.ManualCooking
                    }
                  ]"
                >
                  <view
                    :class="[
                      'block',
                      {
                        active: formData.forwardSpeed >= 7 - v
                      }
                    ]"
                    v-for="v in 6"
                    :key="v"
                    @click="handleForwardSpeedChange(7 - v)"
                  >
                    {{ 7 - v }}
                  </view>
                </view>
              </view>
              <view class="lcr-item" style="flex: initial">
                <view class="lcr-top">
                  <view class="lcrt-left">停止</view>
                </view>
                <view
                  :class="[
                    'list-slider',
                    'list-slider-stop',
                    {
                      disabled: deviceRow.status !== deviceStatus.ManualCooking
                    }
                  ]"
                >
                  <view
                    :class="[
                      'block',
                      {
                        active: formData.forwardSpeed >= 0
                      }
                    ]"
                    @click="handleForwardSpeedChange(0)"
                  >
                    0
                  </view>
                </view>
              </view>
              <view class="lcr-item">
                <view class="lcr-top" style="justify-content: flex-end">
                  <view class="lcrt-left">反转速度</view>
                  <view class="lcrt-right">{{ formData.reverseSpeed }}档</view>
                </view>
                <view
                  :class="[
                    'list-slider',
                    'list-slider-reverse',
                    {
                      disabled: deviceRow.status !== deviceStatus.ManualCooking
                    }
                  ]"
                >
                  <view
                    :class="[
                      'block',
                      {
                        active: formData.reverseSpeed >= v
                      }
                    ]"
                    v-for="(v, i) in 6"
                    :key="v"
                    @click="handleReverseSpeedChange(v)"
                  >
                    {{ v }}
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <view
        v-if="foodBoxList.length || spiceBoxList.length"
        class="lists lists2"
      >
        <view v-if="foodBoxList.length" class="list">
          <view class="list-top" />
          <view class="list-items">
            <view
              class="li-item"
              :class="{
                active: formData.foodBoxDriverId === row.driverId
              }"
              v-for="(row, i) in foodBoxList"
              :key="row.driverId"
              @click="handleRowClick(row)"
            >
              <view class="lii-index">{{ i + 1 }}</view>
              <view class="lii-text">{{ row.name }}</view>
            </view>
          </view>
        </view>
        <view v-if="spiceBoxList.length" class="list">
          <view class="list-ul" style="margin-top: 20rpx">
            <up-checkbox-group
              v-model="formData.seasonBoxDriverId"
              placement="row"
              @change="checkboxChange"
            >
              <view
                class="list-li"
                v-for="(row, i) in spiceBoxList"
                :key="row.driverId"
              >
                <CustomCheckbox
                  :disabled="
                    !row.ingredientRemain ||
                    deviceRow.status !== deviceStatus.ManualCooking ||
                    String(row.status) !== '1'
                  "
                  :name="row.driverId"
                >
                  <template #label>
                    <view class="nw-label">{{ row.ingredientName }}</view>
                  </template>
                </CustomCheckbox>
                <nw-Input
                  v-model.number="row.value"
                  type="number"
                  placeholder=" "
                  verifyType="nzint"
                  :maxlength="4"
                  :clearable="false"
                  :disabled="
                    !row.ingredientRemain ||
                    !formData.seasonBoxDriverId.includes(row.driverId)
                  "
                >
                  <template #right>
                    <view class="unit">{{ boxUnit(row.type) }}</view>
                  </template>
                </nw-Input>
              </view>
              <view
                v-if="(spiceBoxList.length - 1) % 3 === 1"
                style="flex: auto; max-width: calc(33.33% - 25rpx)"
              />
            </up-checkbox-group>
          </view>
        </view>
        <view class="btns">
          <nw-Button
            v-if="deviceRow.status === deviceStatus.Idle"
            text="关机"
            @click="handleShutdown"
          ></nw-Button>
          <nw-Button
            v-if="deviceRow.status === deviceStatus.Idle"
            text="手动洗锅"
            @click="handleManualWashPot"
          ></nw-Button>
          <nw-Button
            v-if="deviceRow.status === deviceStatus.Idle"
            text="自动洗锅"
            @click="handleAutoWashPot"
          ></nw-Button>
          <nw-Button
            v-if="deviceRow.status === deviceStatus.ManualWashPot"
            text="完成洗锅"
            @click="handleCompleteWashPot"
          ></nw-Button>
          <nw-Button
            v-if="deviceRow.status === deviceStatus.ManualCooking"
            text="点击投放"
            @click="handleClickLaunch"
          ></nw-Button>
          <nw-Button
            v-if="deviceRow.status === deviceStatus.WaitPlating"
            text="开始出菜"
            @click="handleDishOut"
          ></nw-Button>
          <nw-Button
            v-if="deviceRow.status === deviceStatus.InPlating"
            text="完成出菜"
            @click="handleCompleteOutPot"
          ></nw-Button>
          <nw-Button
            v-if="deviceRow.status === deviceStatus.WaitPlating"
            text="出菜并保存菜谱"
            @click="handleDishOutSave"
          ></nw-Button>
        </view>
      </view>
    </scroll-view>
  </nw-PageContainer>
  <VoiceControlIcon type="manual" :analysis-source="{...formData, spiceBoxList, foodBoxList, deviceSn: deviceRow.sn}" :check="checkIsManualCooking" @confirm="handleVoice" />
  <nw-Tabbar value="manual" />
</template>

<script setup>
import emitter from '@/utils/emitter'
import { deviceProtocolRecipeService } from '@/service/deviceProtocolRecipeService.js'
import { deviceProtocolManualService } from '@/service/deviceProtocolManualService.js'
import { deviceProtocolEquipmentService } from '@/service/deviceProtocolEquipmentService.js'

const props = defineProps({
  title: {
    type: String,
    default: ''
  }
})

const deviceStore = useDeviceStore()
const { bindDeviceList } = storeToRefs(deviceStore)
const recipeStore = useRecipeStore()
const {getAnGoalByDeviceAndIngredient} = useCookingStore()
const { recipeCategoryList, recipeTempData } = storeToRefs(recipeStore)
const deviceStatus = g_i.device.DeviceStatus
// 模拟设备状态空闲
// bindDeviceList.value.forEach(item => {
//   item.status = 255
// })
const deviceList = computed(() => {
  return bindDeviceList.value.filter(
    item =>
      item.status * 1 === g_i.device.DeviceStatus.Idle ||
      item.status * 1 === g_i.device.DeviceStatus.ManualCooking ||
      recipeTempData.value.sn === item.sn ||
      deviceRow.value.sn === item.sn
  )
})
const uToastRef = ref(null)
const deviceRow = ref({})
const cookingDuration = ref(0)
const statusBtnText = ref('开始')
const formData = ref({
  firepower: 0,
  spatula: 'slewUp',
  forwardSpeed: 0,
  reverseSpeed: 0,
  foodBoxDriverId: '', // 食材盒驱动ID
  seasonBoxDriverId: [] // 调料盒驱动ID
})
const forwardSpeedKey = ref(1) // 重置滑动块的关键key
const reverseSpeedKey = ref(1) // 重置滑动块的关键key
const timer = ref(null)
// 类别参数
const firepowerObj = ref({
  min: 0,
  max: 6
})
const cantileverObj = ref({})
const spatulaObj = ref({})
const foodBoxList = ref([]) // 食材盒列表
const spiceBoxList = ref([]) // 调料盒列表
const boxUnit = type => ([2, 4].includes(type) ? 'g' : 'ml')
// 菜谱数据参数
const MANUAL_RECIPE_ID = '000000000000000' // 菜谱ID为15位的0
const recipeStepList = ref([])

watch(
  () => bindDeviceList.value,
  (nv, ov) => {
    console.log('watch-bindDeviceList.value', nv)
    if (!deviceRow.value.sn) return
    // 动态匹配每个设备的盒类数据
    const deviceObj = nv.find(item => item.sn === deviceRow.value.sn)
    deviceRow.value.status = deviceObj.status
  },
  {
    deep: true
  }
)

onMounted(() => {
  if (recipeTempData.value.sn) {
    const deviceInfo = JSON.parse(
      JSON.stringify(
        bindDeviceList.value.find(
          item => item.sn === recipeTempData.value.sn
        ) || {}
      )
    )
    // 设备信息是手动炒菜状态才赋值
    if (deviceInfo.status === deviceStatus.ManualCooking) {
      deviceRow.value = deviceInfo
      statusBtnText.value = '完成'
      // 计算烹饪时间
      const cookingTime = parseInt(
        (Date.now() - recipeTempData.value.startTime) / 1000
      )
      cookingDuration.value = cookingTime > 0 ? cookingTime * 1 : 0
      timer.value && clearInterval(timer.value)
      timer.value = setInterval(() => {
        cookingDuration.value++
      }, 1000)
      nextTick(() => {
        initDevicePeripheral()
        initManualData()
      })
    }
  }
  recipeStore.setRecipeCategoryList()
  // 监听事件
  emitter.on('device-manual-add-seasoning-result', data => {
    // {"deviceSn":"N21250523152535","driverId":"2201","result":1}
    g_utils.writeLog('收到调料投放结果事件:', data)
    updateRecipeStep(data)
  })
})

// 初始化设备外设信息
const initDevicePeripheral = _ => {
  if (!deviceRow.value.sn) return
  // 动态匹配每个设备的盒类数据
  const deviceObj = bindDeviceList.value.find(
    item => item.sn === deviceRow.value.sn
  )
  const list = g_.cloneDeep(deviceObj.peripheralList || [])
  if (!list.length) return
  // 获取火力值
  firepowerObj.value = list.find(item => item.type === 6)
  // 修改火力的最大值与最小值
  const firepowerList = recipeCategoryList.value
    .find(item => item.value === 'heater')
    .ingredientList.map(item => item.value.slice(-1) * 1)
    .sort()
  firepowerObj.value.min = firepowerList[0]
  firepowerObj.value.max = firepowerList[firepowerList.length - 1]
  // 设置火力默认值
  formData.value.firepower =
    list.find(item => item.type === 6).ingredientCode.slice(-1) * 1
  // 获取悬臂
  cantileverObj.value = list.find(item => item.type === 8)
  // 获取拌刀
  spatulaObj.value = list.find(item => item.type === 7)
  // 获取食材盒和调料盒数据
  foodBoxList.value =
    g_.cloneDeep(list).filter(item => {
      if (item.type === 1) {
        item.value = 1
        return true
      }
    }) || []
  spiceBoxList.value =
    g_.cloneDeep(list).filter(item => {
      if ([2, 3, 4, 5].includes(item.type) && item.ingredientName) {
        item.value = ''
        return true
      }
    }) || []
  console.log('firepowerObj.value', firepowerObj.value)
  console.log('foodBoxList.value', foodBoxList.value)
  console.log('spiceBoxList.value', spiceBoxList.value)
}

// 手动操作数据初始化
const initManualData = _ => {
  console.log('recipeTempData.value', recipeTempData.value)
  const { stepList } = recipeTempData.value
  if (!stepList?.length) return
  recipeStepList.value = g_.cloneDeep(stepList)
  const findStep = type =>
    stepList.reverse().find(item => item.ingredientType === type)?.goal || 0
  // 火力
  formData.value.firepower = findStep('heater')
  // 悬臂
  const cantileverGoal = findStep('cantilever')
  formData.value.spatula = cantileverGoal * 1 === 1 ? 'slewDown' : 'slewUp'
  // 区分是正转还是反转
  const spatulaGoal = findStep('shovel')
  if (spatulaGoal > 128) {
    formData.value.reverseSpeed = spatulaGoal - 128
  } else {
    formData.value.forwardSpeed = spatulaGoal * 1
  }
}

onBeforeUnmount(_ => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
  // 组件销毁时移除监听
  emitter.off('device-manual-add-seasoning-result')
})

// onUnload(() => {
//   if (timer.value) {
//     clearInterval(timer.value)
//     timer.value = null
//   }
//   // 组件销毁时移除监听
//   emitter.off('device-manual-add-seasoning-result')
// })

const handleRoleChange = e => {
  console.log('handleRoleChange:', e)
  deviceRow.value = JSON.parse(JSON.stringify(e))
  statusBtnText.value = '开始'
  clearInterval(timer.value)
  cookingDuration.value = 0
  initDevicePeripheral()
}

// 获取手动操作的菜谱步骤
const setRecipeStep = async item => {
  const [valueArr, labelArr] = g_busTool.findAllValues(
    recipeCategoryList.value,
    item.ingredientCode
  )
  console.log('recipeCategoryList.value', recipeCategoryList.value)
  console.log('item', item)
  console.log('valueArr', valueArr)
  console.log('labelArr', labelArr)
  const ingredientType = valueArr[0] || ''
  const ingredientName = labelArr[labelArr.length - 1] || ''
  const target = valueArr[valueArr.length - 1] || ''
  const goal = (item.value || 0) * 1
  const turnCount = ingredientType === 'material' ? 1 : '' // 食材才有翻转次数
  // const { data } = await g_api.user.apiGetSystemTime()

  recipeStepList.value.push({
    name: g_busTool.getRecipeStepName({
      ingredientType,
      ingredientName,
      materialList: [
        {
          ingredientName,
          goal
        }
      ],
      goal,
      turnCount
    }),
    driverId: item.driverId,
    ingredientType,
    ingredientName,
    target,
    targetId: g_busTool.getRecipeTargetId({
      ingredientType,
      target
    }),
    goal,
    turnCount,
    startTime: Date.now(),
    timeOffset: ''
  })
  console.log('recipeStepList.value', recipeStepList.value)
}

const toastTip = (type = 1, message = '操作成功') => {
  // 1-成功 0-失败
  uToastRef.value.show({
    type: type ? 'success' : 'error',
    message,
    duration: 2000
  })
}

// 修改手动操作的菜谱步骤
const updateRecipeStep = item => {
  console.log('updateRecipeStep', item)
  const i = recipeStepList.value.findIndex(
    step => step.driverId === item.driverId
  )
  const stepData = recipeStepList.value[i]
  const driverId = stepData.driverId
  // result 1-成功=>计算步骤时长 0-失败=>删除该步骤
  if (item.result) {
    // 计算步骤时长，如果小于1秒，则设置为1秒
    const timeOffset = ((Date.now() - stepData.startTime) / 1000).toFixed(0) * 1
    stepData.timeOffset = timeOffset >= 1 ? timeOffset : 1

    delete stepData.startTime
    delete stepData.driverId
  } else {
    // 提示调料失败信息
    toastTip(0, `调料【${stepData.ingredientName}】投发失败`)
    recipeStepList.value.splice(i, 1)
  }
  // 清空页面选择的食材与调料
  formData.value.foodBoxDriverId = ''
  const j = formData.value.seasonBoxDriverId.indexOf(driverId)
  j !== -1 && formData.value.seasonBoxDriverId.splice(j, 1)
  spiceBoxList.value.forEach(list => {
    if (list.driverId === driverId) list.value = ''
  })
  console.log('recipeStepList.value', recipeStepList.value)
  // 记录手机操作的临时数据
  recipeTempData.value = {
    sn: deviceRow.value.sn,
    startTime: recipeTempData.value.startTime || Date.now(),
    stepList: g_.cloneDeep(recipeStepList.value)
  }
}

// --- 指令发送逻辑 ---
const sendCookCommand = (service, method, params = [], execute, item) => {
  uni.showLoading({ title: '指令处理中...', mask: true })
  return service[method](deviceRow.value.sn, ...params)
    .then(r => {
      g_utils.writeLog(`${service}-${method}-发送消息成功：`, r)
      toastTip()
      execute && updateRecipeStep({ ...item, result: 1 })
      return r
    })
    .catch(e => {
      g_utils.writeLog(`${service}-${method}-发送消息失败：`, e)
      toastTip(0, e)
      execute && updateRecipeStep(item)
      throw e
    })
    .finally(() => uni.hideLoading())
}

const handleCook = _ => {
  console.log('handleCook:')
  if (deviceRow.value.sn) {
    if (deviceRow.value.status === deviceStatus.Idle) {
      // 发送开始炒菜指令
      timer.value && clearInterval(timer.value)
      // statusBtnText.value = '完成'
      // timer.value = setInterval(() => cookingDuration.value++, 1000)
      // // 更新设备的状态值为炒菜中
      // deviceStore.updateDeviceStatus(
      //   deviceRow.value.sn,
      //   deviceStatus.ManualCooking
      // )
      // deviceRow.value.status = deviceStatus.ManualCooking
      sendCookCommand(deviceProtocolRecipeService, 'startCooking', [
        MANUAL_RECIPE_ID
      ])
        .then(() => {
          statusBtnText.value = '完成'
          timer.value = setInterval(() => cookingDuration.value++, 1000)
          // 更新设备的状态值为炒菜中
          deviceStore.updateDeviceStatus(
            deviceRow.value.sn,
            deviceStatus.ManualCooking
          )
          deviceRow.value.status = deviceStatus.ManualCooking
        })
        .catch(() => (recipeTempData.value = {})) // 清空手动操作数据
      // 发送油烟机指令
      if (deviceRow.value.bindOil) {
        uni.showLoading({
          title: '指令处理中...',
          mask: true
        })
        deviceProtocolEquipmentService
          .rangeHoodFanControl(deviceRow.value.sn, 1, 1)
          .then(r => {
            g_utils.writeLog('rangeHoodFanControl-发送消息成功：', r)
          })
          .catch(e => {
            g_utils.writeLog('rangeHoodFanControl-发送消息失败：', e)
          })
          .finally(_ => {
            uni.hideLoading()
          })
      }
    } else if (deviceRow.value.status === deviceStatus.ManualCooking) {
      // clearInterval(timer.value)
      // deviceStore.updateDeviceStatus(
      //   deviceRow.value.sn,
      //   deviceStatus.WaitPlating
      // )
      // deviceRow.value.status = deviceStatus.WaitPlating
      // 发送终止炒菜指令
      sendCookCommand(deviceProtocolRecipeService, 'stopCooking').then(() => {
        clearInterval(timer.value)
        deviceStore.updateDeviceStatus(
          deviceRow.value.sn,
          deviceStatus.WaitPlating
        )
        deviceRow.value.status = deviceStatus.WaitPlating
      })
    }
  }
}

// const handleFirepowerChange = g_.debounce(e => {
const handleFirepowerChange = e => {
  console.log('handleFirepowerChange:', e)
  if (deviceRow.value.status !== deviceStatus.ManualCooking) return
  formData.value.firepower = e
  const item = {
    ...firepowerObj.value,
    ingredientCode: firepowerObj.value.ingredientCode + e,
    value: e
  }
  setRecipeStep(item)
  sendCookCommand(
    deviceProtocolManualService,
    'manualAddSeasoning',
    [
      [
        {
          driverId: firepowerObj.value.driverId,
          goal: e
        }
      ]
    ],
    true,
    item
  )
}
// }, 300)

const handleSpatulaSwitch = type => {
  console.log('handleSpatulaSwitch:', type, cantileverObj.value)
  if (deviceRow.value.status !== deviceStatus.ManualCooking) return
  const goal = type === 1 ? 1 : 0
  const item = {
    ...cantileverObj.value,
    ingredientCode: cantileverObj.value.ingredientCode + goal,
    value: goal
  }
  setRecipeStep(item)
  sendCookCommand(
    deviceProtocolManualService,
    'manualAddSeasoning',
    [
      [
        {
          driverId: cantileverObj.value.driverId,
          goal: goal
        }
      ]
    ],
    true,
    item
  ).then(() => {
    formData.value.spatula = type === 1 ? 'slewDown' : 'slewUp'
  })
}

// const handleForwardSpeedChange = g_.debounce(e => {
const handleForwardSpeedChange = e => {
  console.log('handleForwardSpeedChange:', e)
  if (deviceRow.value.status !== deviceStatus.ManualCooking) return
  formData.value.forwardSpeed = e
  formData.value.reverseSpeed = 0
  reverseSpeedKey.value++
  const item = {
    ...spatulaObj.value,
    ingredientCode: spatulaObj.value.ingredientCode + e,
    value: e
  }
  setRecipeStep(item)
  sendCookCommand(
    deviceProtocolManualService,
    'manualAddSeasoning',
    [
      [
        {
          driverId: spatulaObj.value.driverId,
          goal: e
        }
      ]
    ],
    true,
    item
  )
}
// }, 300)

// const handleReverseSpeedChange = g_.debounce(e => {
const handleReverseSpeedChange = e => {
  console.log('handleReverseSpeedChange:', e)
  if (deviceRow.value.status !== deviceStatus.ManualCooking) return
  formData.value.reverseSpeed = e
  formData.value.forwardSpeed = 0
  forwardSpeedKey.value++
  const goal = e ? e + 128 : e
  const item = {
    ...spatulaObj.value,
    ingredientCode: spatulaObj.value.ingredientCode + goal,
    value: goal
  }
  setRecipeStep(item)
  sendCookCommand(
    deviceProtocolManualService,
    'manualAddSeasoning',
    [
      [
        {
          driverId: spatulaObj.value.driverId,
          goal
        }
      ]
    ],
    true,
    item
  )
}
// }, 300)

const handleRowClick = row => {
  console.log('handleRowClick', row)
  // if (!row.driverId) {
  //   toastTip(0, '该食材盒未设置外设驱动ID，请设置')
  //   return
  // }
  if (deviceRow.value.status === deviceStatus.ManualCooking) {
    formData.value.foodBoxDriverId = row.driverId
  }
}

const checkboxChange = e => {
  console.log('checkboxChange', e)
}

const handleShutdown = _ => {
  console.log('handleShutdown')
  sendCookCommand(deviceProtocolManualService, 'shutdownDevice').then(r => {
    deviceStore.updateDeviceStatus(deviceRow.value.sn, deviceStatus.Shutdown)
    deviceRow.value.status = deviceStatus.Shutdown
  })
}
const handleManualWashPot = _ => {
  console.log('handleManualWashPot')
  sendCookCommand(deviceProtocolManualService, 'startManualWashPot').then(r => {
    deviceStore.updateDeviceStatus(
      deviceRow.value.sn,
      deviceStatus.ManualWashPot
    )
    deviceRow.value.status = deviceStatus.ManualWashPot
  })
}

const handleAutoWashPot = _ => {
  console.log('handleAutoWashPot')
  sendCookCommand(deviceProtocolRecipeService, 'startAutoWashPot').then(r => {
    deviceStore.updateDeviceStatus(deviceRow.value.sn, deviceStatus.AutoWashPot)
    deviceRow.value.status = deviceStatus.AutoWashPot
  })
}

const handleCompleteWashPot = _ => {
  console.log('handleCompleteWashPot')
  sendCookCommand(deviceProtocolManualService, 'finishManualWashPot').then(
    r => {
      deviceStore.updateDeviceStatus(deviceRow.value.sn, deviceStatus.Idle)
      deviceRow.value.status = deviceStatus.Idle
    }
  )
}

const handleClickLaunch = _ => {
  console.log('handleClickLaunch')
  // 获取调料盒的数据，包括编码和重量
  const boxDriverIdList = [
    formData.value.foodBoxDriverId,
    ...formData.value.seasonBoxDriverId
  ].filter(Boolean)
  console.log('boxDriverIdList', boxDriverIdList)

  if (!boxDriverIdList.length) {
    toastTip(0, '请选择食材或调料')
    return
  }
  for (const list of spiceBoxList.value) {
    // 食材盒不需填写重量
    if (formData.value.seasonBoxDriverId.includes(list.driverId)) {
      console.log('list', list)
      if (!list.value) {
        toastTip(0, `所选调料【${list.ingredientName}】的值不能为空`)
        return
      }
      // 检查调料剩余量是否充足
      if (list.value > list.ingredientRemain) {
        toastTip(
          0,
          `调料盒【${list.ingredientName}】剩余数量为${
            list.ingredientRemain
          }${boxUnit(list.type)}，请添加调料`
        )
        return
      }
    }
  }

  const prevStepList = []
  const seasoningBoxList = [...foodBoxList.value, ...spiceBoxList.value].reduce(
    (prev, cur) => {
      if (boxDriverIdList.includes(cur.driverId)) {
        let goal = cur.value * 1
        if ([2, 3, 4, 5].includes(cur.type)) {
          // 调料盒需要传入重量值
          goal = getAnGoalByDeviceAndIngredient(cur.ingredientCode, deviceRow.value, goal)
        }
        prev.push({
          driverId: cur.driverId,
          goal
        })
        prevStepList.push(cur)
      }
      return prev
    },
    []
  )
  console.log('seasoningBoxList', seasoningBoxList)
  console.log('prevStepList', prevStepList)
  prevStepList.forEach(item => {
    setRecipeStep(item)
  })

  // setTimeout(() => {
  //   seasoningBoxList.forEach((item, i) => {
  //     item.result = 1
  //     if (i === 1) item.result = 0
  //     updateRecipeStep(item)
  //   })
  // }, 1500)

  sendCookCommand(deviceProtocolManualService, 'manualAddSeasoning', [
    seasoningBoxList
  ])
    .then(r => {
      seasoningBoxList.forEach(item => {
        updateRecipeStep({ ...item, result: 1 })
      })
    })
    .catch(e => {
      seasoningBoxList.forEach(item => {
        updateRecipeStep(item)
      })
    })
}

const handleDishOut = _ => {
  console.log('handleDishOut')
  sendCookCommand(deviceProtocolRecipeService, 'startPlating').then(r => {
    deviceStore.updateDeviceStatus(deviceRow.value.sn, deviceStatus.InPlating)
    deviceRow.value.status = deviceStatus.InPlating
  })
}

const handleCompleteOutPot = _ => {
  console.log('handleCompleteOutPot')
  sendCookCommand(deviceProtocolRecipeService, 'finishPlating').then(r => {
    deviceStore.updateDeviceStatus(deviceRow.value.sn, deviceStatus.Resting)
    deviceRow.value.status = deviceStatus.Resting
    // 设备复位
    statusBtnText.value = '开始'
    clearInterval(timer.value)
    cookingDuration.value = 0
    // 数据重置和清空
    formData.value = {
      firepower: 0,
      spatula: 'slewUp',
      forwardSpeed: 0,
      reverseSpeed: 0,
      foodBoxDriverId: '',
      seasonBoxDriverId: []
    }
    recipeTempData.value = {}
  })
}

const handleDishOutSave = _ => {
  console.log('handleDishOutSave', recipeStepList.value)
  sendCookCommand(deviceProtocolRecipeService, 'startPlating').then(r => {
    deviceStore.updateDeviceStatus(deviceRow.value.sn, deviceStatus.InPlating)
    deviceRow.value.status = deviceStatus.InPlating
    recipeTempData.value = {
      id: g_busTool.getRecipeId(),
      stepList: g_.cloneDeep(recipeStepList.value)
    }
    uni.navigateTo({
      url: `/pages/recipe/detail?type=manual&recipeType=1`
    })
  })
}

const checkIsManualCooking = _ => {
  return deviceRow.value.status === deviceStatus.ManualCooking
}

const handleVoice = voiceData => {
  console.log('handleVoice', voiceData)
  if (deviceStatus.ManualCooking !== deviceRow.value.status) {
    toastTip(0, '当前设备不在手动炒菜状态，无法使用语音控制')
    return
  }

  switch(voiceData.action) {
    case 'handleFirepowerChange':
        handleFirepowerChange(voiceData.value)
        break
    case 'handleForwardSpeedChange':
        handleForwardSpeedChange(voiceData.value)
        break
    case 'handleReverseSpeedChange':
        handleReverseSpeedChange(voiceData.value)
        break
    case 'handleSpatulaSwitch':
        handleSpatulaSwitch(voiceData.code)
        break
    case 'handleClickLaunch':
        if (voiceData.type != '1') {
          formData.value.foodBoxDriverId = voiceData.driverId
        } else {
          formData.value.seasonBoxDriverId = [voiceData.driverId]
          spiceBoxList.find(val => {
            if (val.driverId == voiceData.driverId) {
              val.value = voiceData.value
              return true
            }
          })
        }
        handleClickLaunch()
        break
    default:
        break
  }
}
</script>

<style lang="scss" scoped>
@import './scss/index.scss';
</style>
